package com.cf.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.cf.domain.FileUploadResponse;
import com.cf.domain.ImagesData;
import com.cf.domain.ResponseResult;
import com.cf.domain.vo.TeamVO;
import com.cf.domain.vo.UserVO;
import com.cf.enums.UserRole;
import com.cf.exception.MyException;
import com.cf.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequiredArgsConstructor
public class UploadController {

    @Value("${cf.file.upload-dir}")
    private String upload;

    @Value("${cf.file.download-dir}")
    private String download;


    @Value("${cf.file.view-dir}")
    private String httpUrl;

    private final IUserService userService;


    @PostMapping("/upload")
    @ResponseBody
    public ResponseResult upload(@RequestParam("file") MultipartFile file) throws IOException {
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        int dotx = originalFilename.lastIndexOf(".");
        String extension = originalFilename.substring(dotx);
        String path = UUID.randomUUID().toString();

        //文件格式为doc、docx、pdf、mp4、avi
        if(!extension.equals(".doc")&&!extension.equals(".docx")&&!extension.equals(".pdf")&&!extension.equals(".mp4")&&!extension.equals(".avi")){
            throw new MyException("文件格式只能是doc、docx、pdf、mp4、avi！");
        }
        path = path + extension;
        File file1 = new File(upload + path);
        if(!file1.exists()){
            file1.mkdirs();
        }
        //将文件存储在服务器的磁盘目录
        file.transferTo(file1);
        return ResponseResult.sucess(path);
    }

    @GetMapping("/download/{fileName:.+}")
    public ResponseEntity<Resource> download(@PathVariable String fileName) throws IOException {
        Path filePath = Paths.get(upload).resolve(fileName).normalize();
        Resource resource = new org.springframework.core.io.FileUrlResource(filePath.toUri().toURL());

        if (!resource.exists()) {
            throw new FileNotFoundException("找不到文件： " + fileName);
        }

        // 设置下载文件的响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"");

        return ResponseEntity.ok()
                .headers(headers)
                .body(resource);
    }

    /**
     * 非项目路径下的图片显示接口
     * @param imageName
     * @param response
     */
    @GetMapping("/accessExternalImage/{imageName}")
    @ResponseBody
    public void accessExternalImage(@PathVariable("imageName") String imageName, HttpServletResponse response) {
        File imageFile = new File(upload + "images/" + imageName);
        if (imageFile.exists()) {
            try {
                FileInputStream fis = new FileInputStream(imageFile);
                response.setContentType(MediaType.IMAGE_JPEG_VALUE); // 根据图片实际格式设置ContentType，这里假设是JPEG格式
                OutputStream os = response.getOutputStream();
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = fis.read(buffer))!= -1) {
                    os.write(buffer, 0, bytesRead);
                }
                fis.close();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 图片上传接口
    @PostMapping("/uploadImage")
    @ResponseBody
    public ResponseEntity<?> uploadImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return new ResponseEntity<>("请选择要上传的图片", HttpStatus.BAD_REQUEST);
        }

        // 生成唯一的文件名
        String fileName = UUID.randomUUID().toString() + "." + getFileExtension(file.getOriginalFilename());

        // 定义图片保存路径，这里假设保存到项目的upload目录下，可根据实际情况调整
        String savePath = upload + "images/" + fileName;
        File dest = new File(savePath);

        try {
            // 保存图片到指定路径
            file.transferTo(dest);
            // 返回图片的访问路径，这里假设项目部署后可通过 /upload/{文件名} 访问到图片，需根据实际情况调整
            // 创建返回结果对象
            FileUploadResponse fileUploadResponse = new FileUploadResponse();
            fileUploadResponse.setCode(0);
            fileUploadResponse.setMsg("上传成功");
            ImagesData data = new ImagesData();
            data.setSrc(httpUrl + fileName);
            data.setTitle("");
            fileUploadResponse.setData(data);
            return new ResponseEntity<>(fileUploadResponse, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>("图片上传失败", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

//    @GetMapping("/downloads")
//    @ResponseBody
//    public ResponseResult downloads(){
//        Map<String, Object> map = new HashMap<>();
//        map.put("areaSearch", "0");
//        UserVO userVO = new UserVO();
//        userVO.setUserRole(1);
//        userVO.setArea(0);
//        List<TeamVO> data = userService.selectMembers(map, userVO);
//        for(TeamVO team:data){
//            String filePath = "E:/data/" + team.getName() + "(" + team.getPhone() + ")";
//            File file = new File(filePath);
//            if(!file.exists()){
//                if (file.mkdir()) {
//                    System.out.println(file.getPath() + "文件夹创建成功！开始移动文件");
//                } else {
//                    System.out.println("文件夹创建失败！");
//                }
//            }
//            if(team.getTeam() != null){
//                if(team.getTeam().getPlan() != null && !StringUtils.isBlank(team.getTeam().getPlan())){
//                    String sourcePath = upload + team.getTeam().getPlan();
//                    File source = new File(sourcePath);
//
//                    String pex = sourcePath.substring(sourcePath.lastIndexOf("."));
//                    String targetPath = filePath + "/" + "项目计划书" + pex;
//                    File target = new File(targetPath);
//
//                    if(source.renameTo(target)){
//                        System.out.println(sourcePath + "1移动成功到 " + targetPath);
//                    }else{
//                        System.out.println("*********1移动失败"+sourcePath + "移动到 " + targetPath);
//                    }
//                }
//                if(team.getTeam().getVideo() != null && !StringUtils.isBlank(team.getTeam().getVideo())){
//                    String sourcePath = upload + team.getTeam().getVideo();
//                    File source = new File(sourcePath);
//
//                    String pex = sourcePath.substring(sourcePath.lastIndexOf("."));
//                    String targetPath = filePath + "/" + "项目介绍" + pex;
//                    File target = new File(targetPath);
//
//                    if(source.renameTo(target)){
//                        System.out.println(sourcePath + "2移动成功到 " + targetPath);
//                    }else{
//                        System.out.println("*********2移动失败"+sourcePath + "移动到 " + targetPath);
//                    }
//                }
//            }
//        }
//        return ResponseResult.sucess();
//    }

    // 获取文件扩展名的方法
    private String getFileExtension(String fileName) {
        return fileName.substring(fileName.lastIndexOf('.') + 1);
    }
}
